from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .serializer import *
from .models import *
# Create your views here.

class AuthorView(APIView):
    def post(self,request):
        user = request.data.get('username')
        pwd = request.data.get('password')
        ca = Author.objects.filter(username=user).first()
        if ca and ca.password == pwd:
            return Response({'msg':'OK','code':200,'id':ca.id,'user':ca.username})
        else:
            return Response({'msg':'失败','code':400})

class BooksView(APIView):
    def post(self,request):
        ca = BooksSer(data=request.data)
        ca.is_valid(raise_exception=True)
        ca.save()
        return Response({'msg':'图书添加成功'})

    def get(self,request):
        id = request.query_params.get('id')
        if not id:
            page = int(request.query_params.get('page', 1))
            size = 2
            start = (page - 1) * size
            end = page * size
            ca_li = Books.objects.all()[start:end]
            total = Books.objects.all().count()
            ca = BooksSer(ca_li,many=True)
            return Response({'ca':ca.data,'total':total})
        else:

            ca_li = Books.objects.filter(id=id)
            ca = BooksSer(ca_li,many=True)
            return Response({'ca':ca.data})

